<template>
  <div class="goodsdetails bg-hex-F5F5F5">
    <div class="sticky left-0 right-0 top-0 z-9 h-full bg-hex-ffffff">
      <div v-if="scroll_value < top_nav_height" class="relative">
        <div class="absolute top-0 z-999 flex items-center px-20rpx" :style="{ paddingTop: `${searchBarTop}px` }" @click.stop="goback">
          <uni-icons type="back" style="color: #333;" size="28" />
        </div>
      </div>
      <trn-nav v-else :propScroll="scroll_value" :propHeight="top_nav_height">
        <div class="absolute top-0 z-999 flex items-center px-20rpx" :style="{ paddingTop: `${searchBarTop}px` }" @click.stop="goback">
          <uni-icons type="back" style="color: #333;" size="28" />
        </div>
      </trn-nav>
    </div>
    <swiper v-if="detailBanner" autoplay circular class="min-h-482rpx" :style="{ paddingTop: `${searchBarTop+35}px` }">
      <swiper-item v-for="item in detailBanner">
        <image :src="item" class="w-100%" mode="widthFix" />
      </swiper-item>
    </swiper>
    <div class="m-28rpx rounded-16rpx bg-hex-fff">
      <div class="flex justify-between pl-24rpx pt-28rpx">
        <div class="flex items-end">
          <div class="flex items-end text-44rpx text-hex-ff4d4e">{{ finallPrice }}
            <div class="text-24rpx text-hex-ff4d4e">元</div>
          </div>
          <div class="textdecor ml-22rpx text-26rpx text-hex-999">{{ goodsDetail.cost }}元</div>
        </div>
        <!-- <div
          class="h-50rpx rounded-bl-full rounded-tl-full px-30rpx text-28rpx font-400 leading-50rpx text-hex-fff shadow">
          去分享
        </div> -->
        <div>
          <button open-type="share" data-name="shareFood"
                  class="h-50rpx rounded-bl-full rounded-tl-full px-30rpx text-28rpx font-400 leading-50rpx text-hex-fff shadow">去分享</button>
        </div>

      </div>
      <div class="p-25rpx text-30rpx font-600 text-hex-333">{{ goodsDetail.productName }}</div>
      <div class="flex items-center justify-between px-25rpx pb-25rpx">
        <div class="text-26rpx font-500 text-hex-999">销量：{{ goodsDetail.saleNum }}{{ goodsUnit }}</div>
      </div>
    </div>
    <div class="m-28rpx rounded-16rpx bg-hex-fff">
      <div
        class="box-border flex items-center justify-between border-2rpx border-hex-eee border-b-solid p-25rpx"
        @click="openSpecsDialog">
        <div class="flex">
          <div class="text-26rpx font-400 text-hex-999">{{ isSelectAttribute?'已选择':'请选择' }}：</div>
          <div class="text-26rpx font-500 text-hex-333">{{ selectAttributeText }}</div>
        </div>
        <div class="arrow-right" />
      </div>
      <div class="box-border flex items-center justify-between p-25rpx" @click="goUrl(`/pages-tea/userComment?productId=${productId}`)">
        <div class="text-26rpx font-500 text-hex-333">用户评价({{ evaluationNumber }})</div>
        <div class="arrow-right" />
      </div>
    </div>
    <div class="flex items-center justify-center">
      <div class="flex items-center">
        <div class="bggarden-left h-2rpx w-74rpx" />
        <div class="h-8rpx w-8rpx border-2rpx border-hex-666 rounded-full border-solid" />
      </div>
      <div class="px-20rpx text-28rpx font-500 text-hex-666">商品详情</div>
      <div class="flex items-center">
        <div class="h-8rpx w-8rpx border-2rpx border-hex-666 rounded-full border-solid" />
        <div class="bggarden-right h-2rpx w-74rpx" />
      </div>
    </div>
    <!-- 详情 -->
    <div v-if="textContent" id="editor" class="m-28rpx">
      <!-- <div class="h-200rpx w-full rounded-20rpx bg-hex-c4c4c4" /> -->
      <rich-text :nodes="textContent" />
    </div>
    <!-- 推荐商品 -->
    <div class="mt-40rpx flex items-center justify-center">
      <div class="h-2rpx w-90rpx bg-hex-f0f0f0" />
      <div class="px-20rpx">推荐商品</div>
      <div class="h-2rpx w-90rpx bg-hex-f0f0f0" />
    </div>
    <div class="mb-32rpx pt-25rpx">
      <div class="box-border rounded-t-32rpx pl-28rpx">
        <s-waterfall :datalist="collectShop" :column="2" :resetwidth="Date.now()" class="mt-32rpx">
          <template #default="{ item }">
            <div class="mb-30rpx mr-28rpx rounded-32rpx bg-hex-fff pb-10rpx" @click.stop="navTo(`/pages-shop/goodsdetails?productId=${item.productId}`)">
              <div class="bg-water box-border w-326rpx flex items-center justify-center rounded-xl bg-hex-FAF9F8 p-40rpx">
                <image
                  class="will-change h-100% w-100% rounded-24rpx"
                  lazy-load
                  :src="item.productImage" mode="widthFix" />
              </div>
              <div class="p-15rpx">
                <div class="mb-10rpx flex items-center">
                  <div
                    v-if="item.newState===1"
                    class="w-48rpx rounded-5rpx bg-hex-FFF2E3 p-3rpx text-20rpx font-500 text-hex-E89C43">
                    上新
                  </div>
                  <text
                    class="multiLine-hiddle hide2 mx-10rpx inline-block text-24rpx text-hex-333">
                    {{ item.productIntro }}</text>
                </div>

                <div class="flex items-center justify-between">
                  <div>
                    <div class="flex items-end">
                      <div class="text-32rpx font-400 text-hex-ff4d4e">¥{{ item.productPrice }}</div>
                      <!-- <div class="textdecor ml-10rpx text-24rpx font-500 text-hex-999">￥{{ item.cost }}</div> -->
                    </div>

                  </div>
                  <div class="textdecor text-24rpx font-500 text-hex-999">已售{{ item.saleNum??0 }}</div>
                </div>
              </div>
            </div>
          </template>
        </s-waterfall>
      </div>
    </div>

    <div class="h-156rpx" />
    <div class="bottomCon fixed bottom-0 w-100% bg-hex-fff pb-20rpx">
      <div><confirm ref="confirmRef" /></div>
      <!-- 购物车底部信息 -->
      <div class="h-176rpx flex items-center justify-around">
        <div class="flex flex-col items-center" @click="goTeaOpenGoodsCar">
          <div class="relative">
            <image
              :src="`${cdnUrl}/imgs/userComment/goodsCar.png${imgVersion}`"
              mode="scaleToFill"
              class="h-60rpx w-60rpx"
            />
            <div
              v-if="goodsCarNum>0"
              class="absolute box-border min-h-42rpx min-w-42rpx flex items-center justify-center border-2rpx border-hex-ffffff rounded-50% border-solid bg-hex-C1A670 text-24rpx text-hex-ffffff -right-10rpx -top-10rpx"
            >{{ goodsCarNum }}</div>
          </div>
          <div class="text-24rpx text-hex-ADADAD">购物车</div>
        </div>
        <div class="flex flex-col items-center">
          <div>
            <image
              :src="`${cdnUrl}/svgicons/pl_save${isCollect}.svg${imgVersion}`"
              mode="scaleToFill"
              class="h-60rpx w-60rpx"
              @click="handelCollect"
            />
          </div>
          <div class="text-24rpx text-hex-ADADAD">{{ isCollect?'取消收藏': '收藏' }}</div>
        </div>
        <div
          class="h-72rpx w-50% border-2rpx border-hex-F2A532 rounded-46rpx border-solid text-center text-26rpx leading-72rpx text-hex-F2A532"
          @click="openSpecsDialog">加入购物车</div>
      </div>
    </div>
    <!-- 规格弹窗 -->
    <uni-popup ref="specspop" background-color="#fff">
      <div class="box-border p-32rpx">
        <div class="mb-48rpx flex justify-between">
          <div class="flex items-end">
            <image
              :src="goodsDetail.productImage"
              mode="scaleToFill"
              class="mr-24rpx h-120rpx w-120rpx rounded-8rpx"
            />
            <div class="flex items-end text-48rpx text-hex-FF5A5A"><text class="text-28rpx">¥</text>{{ finallPrice }}</div>
          </div>
          <div @click="closeSpecsDialog">
            <image
              :src="`${cdnUrl}/imgs/shopSpecsPop/specscancel.png${imgVersion}`"
              mode="scaleToFill"
              class="h-32rpx w-32rpx"
            />
          </div>
        </div>
        <!-- 规格选择 -->
        <div v-if="attributeList">
          <div
            v-for="item in attributeList"
            class="mb-48rpx">
            <div class="mb-24rpx text-28rpx font-bold text-hex-333333">{{ item.name }}</div>
            <div class="flex">
              <div
                v-for="tag in item.childList"
                :class="item?.val?.id===tag?.id?'text-hex-ABCD03 border-2rpx border-hex-ABCD03 border-solid':'text-hex-999'"
                class="mr-30rpx box-border rounded-28rpx bg-hex-F5F5F5 px-16rpx py-8rpx text-28rpx text-hex-999999"
                @click="selectOption(item, tag)">{{ tag.name }}</div>
            </div>
          </div>
        </div>
        <!-- 数量 -->
        <div class="mb-64rpx flex justify-between">
          <div class="flex items-end text-28rpx font-bold text-hex-333333">数量<text class="ml-8rpx text-20rpx font-500 text-hex-8995AD">{{ Number(strokeNum)>0?'有货':'暂无库存' }}</text></div>
          <div class="box-border inline-block flex items-center rounded-30rpx bg-hex-F1F3F5 px-16rpx py-8rpx">
            <image
              :src="`${cdnUrl}/svgicons/userComment/down.svg${imgVersion}`"
              mode="scaleToFill"
              class="h-44rpx w-44rpx"
              @click="reduceGoodsNum"
            />
            <div class="mx-20rpx text-28rpx text-hex-50566">{{ goodsNum }}</div>
            <image
              :src="`${cdnUrl}/svgicons/userComment/add.svg${imgVersion}`"
              mode="scaleToFill"
              class="h-44rpx w-44rpx"
              @click="addGoodsNum"
            />
          </div>
        </div>
        <!-- 按钮 -->
        <div class="mb-64rpx flex justify-between text-28rpx">
          <div
            class="h-72rpx w-100% border-2rpx border-hex-F2A532 rounded-46rpx border-solid text-center leading-72rpx text-hex-F2A532"
            @click="addGoodsCar"
          >加入购物车</div>
        </div>
      </div>
    </uni-popup>
  </div>
</template>

<script setup lang="ts">
import { useUserStore } from '@/stores/user'
import { useAddressStore } from '@/stores/address'
import { useShopStore } from '@/stores/shop'
import { useLoginStore } from '@/stores/login'

const loginStore = useLoginStore()
let shopStore: any = useShopStore()
const userStores = useUserStore()

let addressStores: any = useAddressStore()

let searchBarTop: any = $ref('24')
let rightBar: any = $ref(0)
let productId: any = $ref('')
let limitNum: any = $ref(0)
onLoad((options) => {
  // #ifndef H5
  let menuButtonInfo = uni.getMenuButtonBoundingClientRect()
  searchBarTop = menuButtonInfo.top
  rightBar = menuButtonInfo.width
  // #endif
  uni.pageScrollTo({
    scrollTop: 0,
    duration: 300,
  })
  if (options) {
    if (options.scene) {
      productId = options.scene
      uni.setStorageSync('pageScene', `/pages-tea/roundProductDetail?productId=${productId}`)
    } else {
      productId = options.productId
    }
  }

})

onShareAppMessage((res) =>
{
  return {
    title: '心悦',
    path: `/pages-tea/roundProductDetail?scene=${productId}`,
  }
})
onShareTimeline(() =>
{
  return {
    title: '分享朋友圈',
    query: `scene=${productId}`,
  }
})
let isSelectAttribute: any = $ref(false)
let selectAttributeText: any = $ref('购买规格·数量')
let confirmRef: any = $ref('')
let childrenSkus: any = $ref([])
// 规格弹窗
let specspop: any = $ref('')
const openSpecsDialog = () => {
  specspop.open('bottom')
  selectAttributeText = ''
  if (attributeList.length > 0) {
    let tempSelectAttributesList: any = []
    attributeList.forEach((item) => {
      tempSelectAttributesList.push(item?.val?.name)
    })
    selectAttributeText = tempSelectAttributesList.join('/')
    selectAttributeText = `${selectAttributeText} · ${goodsNum}${goodsUnit}`
  } else {
    selectAttributeText = `${goodsNum}${goodsUnit}`
  }
  isSelectAttribute = true
}
const closeSpecsDialog = () => {
  specspop.close()
}
let goodsNum: any = $ref(1)
const addGoodsNum = () => {
  if (goodsDetail.unionFlag === 0) {
    if (goodsNum === limitNum) {
      uni.showToast({
        title: '超过最大购买数量',
        icon: 'none',
      })
      return
    }
  }
  goodsNum++
  selectAttributeText = ''
  if (attributeList.length > 0) {
    let tempSelectAttributesList: any = []
    attributeList.forEach((item) => {
      tempSelectAttributesList.push(item?.val?.name)
    })
    selectAttributeText = tempSelectAttributesList.join('/')
    selectAttributeText = `${selectAttributeText} · ${goodsNum}${goodsUnit}`
  } else {
    selectAttributeText = `${goodsNum}${goodsUnit}`
  }
  isSelectAttribute = true
}
const reduceGoodsNum = () => {
  if (goodsNum === 1) {
    return
  }
  goodsNum--
  selectAttributeText = ''
  if (attributeList.length > 0) {
    let tempSelectAttributesList: any = []
    attributeList.forEach((item) => {
      tempSelectAttributesList.push(item?.val?.name)
    })
    selectAttributeText = tempSelectAttributesList.join('/')
    selectAttributeText = `${selectAttributeText} · ${goodsNum}${goodsUnit}`
  } else {
    selectAttributeText = `${goodsNum}${goodsUnit}`
  }
  isSelectAttribute = true
}
let selectData: any = $ref([])
let skuList: any = $ref([])
let goodsUnit: any = $ref('件')
const filterSkuListSingleOption = (attrs1, attrs2) => {
  if (attrs1.length !== attrs2.length) {
    return false
  }
  for (const attr1 of attrs1) {
    const matchingAttr = attrs2.find(attr2 => attr2.k_id === attr1.k_id && attr2.v_id === attr1.v_id)
    if (!matchingAttr) {
      return false
    }
  }
  return true
}
// 操作加入购物车数据的函数
const handelAddGoodsList = () => {
  selectData = []
  childrenSkus = []
  let attributes: any = []
  attributeList.forEach((item) => {
    selectData.push({
      'k': item?.name,
      'k_id': item?.id,
      'v_id': item.val?.id,
    })
    attributes.push({
      'attributeId': item?.id,
      'attributeValueIds': [item?.val?.id],
    })
  })
  let matchingSKU: any = {}
  matchingSKU = skuList.find((sku: any) => filterSkuListSingleOption(sku.specs, selectData))
  if (Object.keys(matchingSKU).length === 0) {
    uni.showToast({
      title: '库存不足!',
      icon: 'none',
    })
    childrenSkus = []
    return
  }
  finallPrice = matchingSKU.productSkuPrice
  goodsUnit = matchingSKU.productSkuUnit
  limitNum = matchingSKU.stock
  childrenSkus.push({
    'attributes': attributes,
    'productId': goodsDetail.productElementList[0].childProductId,
    'skuId': matchingSKU.id,
  })
}
//选择规格展示
const selectOption = (item, tag) => {
  item.val = tag
  handelAddGoodsList()
  let tempSelectAttributesList: any = []
  attributeList.forEach((item) => tempSelectAttributesList.push(item?.val?.name))
  selectAttributeText = tempSelectAttributesList.join('/')
  selectAttributeText = `${selectAttributeText} · ${goodsNum}${goodsUnit}`
  isSelectAttribute = true
}
//顶部导航
let scroll_value = $ref(0)
let top_nav_height = $ref(50)
onPageScroll((e) => {
  scroll_value = e.scrollTop
})
const goback = () => {
  uni.navigateBack({
    delta: 1,
  })
}
//路由跳转
const goUrl = (url) => {
  if (url) {
    uni.navigateTo({ url })
  }
}
let textContent: any = $ref('')
let goodsDetail: any = $ref({})
let detailBanner: any = $ref([])
let attributeList: any = $ref([])
let strokeNum: any = $ref('')
let finallPrice: any = $ref(0)
const getGoodsDetail = async () => {
  const reqData = {
    method: 'post',
    data: { 'storeId': addressStores.selectStores.id, 'productId': productId, appType: 2 },
    headers: { UserId: userStores.user.id, AppType: 2 },
  }
  const { status, data, error } = await Fetch('/qqyapi/product/product/detail', reqData)
  if (status !== 200 || data.code !== 0) {
    return
  }
  if (data.code === 0) {
    let tempObj: any = data?.result
    goodsDetail = tempObj
    detailBanner = goodsDetail?.productBannerImage.split(',')
    textContent = goodsDetail?.productDetailImage.replace(/style=""/g, 'style="max-width:100% !important;display:block;"')
    if (goodsDetail.unionFlag === 0) {
      attributeList = goodsDetail.productElementList[0].attributeList
      strokeNum = goodsDetail.productElementList[0]?.num
      skuList = goodsDetail.productElementList[0].skuList
      if (skuList.length >= 1) {
        skuList.forEach((item: any) => item.specs = JSON.parse(item.specs))
        attributeList.forEach((itemattr: any) => itemattr.val = itemattr.childList[0])
        handelAddGoodsList()
      } else {
        finallPrice = skuList[0].productSkuPrice
        goodsUnit = skuList[0].productSkuUnit
        limitNum = skuList[0].stock
        childrenSkus.push({
          'attributes': [],
          'productId': goodsDetail.productElementList[0].childProductId,
          'skuId': skuList[0].id,
        })
      }
    } else {
      // goodsDetail.productElementList.forEach((item) => attributeList.concat(item.skuList))
    }
  }
}
// 加入购物车
const addGoodsCar = async () => {
  if (childrenSkus.length === 0) {
    uni.showToast({
      title: '库存不足!',
      icon: 'error',
    })
    return
  }
  const reqData = {
    method: 'post',
    data: {
      'detailDTO': {
        'amount': goodsNum,
        'childrenSkus': childrenSkus,
        'productId': productId,
        'isJoinedActivity': false,
      },
      'trolleyType': 2,
    },
    headers: { UserId: userStores.user.id },
  }
  const { status, data, error } = await Fetch('/qqyapi/order/trolley/addItem', reqData)
  // const { status, data, error } = await Fetch('http://192.168.0.105:8077/trolley/addItem', reqData)
  if (status !== 200 || data.code !== 0) {
    return
  }
  if (data.code === 0) {
    uni.hideLoading()
    closeSpecsDialog()
    uni.showToast({
      title: '商品已加入购物车',
      icon: 'none',
    })
    getGoodsCarNum()
    uni.$emit('handelEvent')
  }
}
let isCollect: any = $ref(false)
// 查询用户是否收藏该商品
const getIsCollect = async () => {
  const reqData = {
    method: 'post',
    data: {
      'productId': productId,
      'storeId': addressStores.selectStores.id,
    },
    headers: {
      AppType: 2,
      UserId: userStores.user.id,
    },
  }
  const { data, status, error } = await Fetch('/qqyapi/product/product/collect/isCollect', reqData)
  if (status !== 200 || data.code !== 0) {
    return
  }
  isCollect = data.result
}
// 收藏，取消收藏
const handelCollect = useThrottleFn(async () => {
  if (!loginStore.roleId) {
    loginStore.setIsBack(true)
    loginStore.isGoLogin()
    return
  }
  const reqData = {
    method: 'post',
    data: {
      'productId': productId,
      'storeId': addressStores.selectStores.id,
    },
    headers: {
      AppType: 2,
      UserId: userStores.user.id,
    },
  }
  const url = isCollect ? '/qqyapi/product/product/collect/delete' : '/qqyapi/product/product/collect/add'
  const { data, status, error } = await Fetch(url, reqData)
  if (status !== 200 || data.code !== 0) {
    return
  }
  getIsCollect()
}, 500)

let evaluationNumber: any = $ref(0)
// 查看商品评价数量
const getGoodsEvaluationNum = async () => {
  const reqData = {
    method: 'post',
    data: {
      'productId': productId,
      'storeId': addressStores.selectStores.id,
    },
    headers: {
      AppType: 2,
      userId: userStores.user.id,
    },
  }
  const { data, status, error } = await Fetch('/qqyapi/product/product/evaluation/countByProductId', reqData)
  if (status !== 200 || data.code !== 0) {
    return
  }
  evaluationNumber = data.result
}
let goodsCarNum: any = $ref(0)
// 获取购物车的数量
const getGoodsCarNum = async () => {
  const reqData = {
    method: 'post',
    data: {
      'storeId': addressStores.selectStores.id,
      'trolleyType': 2,
    },
    headers: { UserId: userStores.user.id },
  }
  const { data, status, error } = await Fetch('/qqyapi/order/trolley/renderTrolleyViewDto', reqData)
  if (status !== 200 || data.code !== 0) {
    return
  }
  if (data.code === 0) {
    const allList = data?.result?.trolleyItemDescDTOList
    goodsCarNum = allList.reduce((sum, item) => sum + item.amount, 0)
  }
}
let collectShop: any = $ref([])
let pageNo = $ref(1)
let totalPage = $ref(0)
//商品推荐数据
const getLikeData = async () => {
  const { data, error, status } = await Fetch('/qqyapi/product/product/categoryArea/recommendProductList', {
    method: 'get',
    data: { appType: 3, pageNo, pageSize: 10 }, //
  })
  if (status === 200 && data.code === 0) {
    collectShop = [...collectShop, ...data.result.list]
    totalPage = data.totalPage
  }
}
//下滑加载更多数据
const getMoreData = () => {
  if (totalPage !== pageNo) {
    pageNo++
    getLikeData()
  }
}
const goTeaOpenGoodsCar = () => {
  uni.switchTab({
    url: '/pages/index',
  })
  uni.$emit('teaIndexOpenTeaGoodsCarPop')
}

onMounted(async () => {
  //获取地址列表
  await addressStores.getListData(userStores.user.id, 1, 10) //默认先获取10条，用来方便处理没有默认地址取第一条
  await addressStores.defaultaddress(userStores.user.id)
  getGoodsDetail()
  getIsCollect()
  getGoodsEvaluationNum()
  getGoodsCarNum()
  getMoreData()
})

</script>

<style scoped lang="scss">
.goodsdetails {
  .textdecor {
    text-decoration: line-through;
  }

  .shadow {
    background: linear-gradient(90deg, #D4392F 0%, #FF9921 100%);
    box-shadow: 0rpx 4rpx 6rpx 0rpx rgb(174 27 33 / 17%);
  }

  .arrow-right {
    width: 12rpx;
    height: 12rpx;
    background-color: transparent;

    /* 模块背景为透明 */
    border-color: #969696;
    border-style: solid;
    border-width: 3rpx 3rpx 0 0;
    transform: rotate(45deg);
  }

  .textHide2 {
    overflow: hidden;
    text-overflow: ellipsis;
    -webkit-line-clamp: 2;
    display: -webkit-box;
    -webkit-box-orient: vertical;
  }

  .textdecor {
    text-decoration: line-through;
  }

  .bggarden-left {
    background: linear-gradient(270deg, #666 0%, rgb(102 102 102 / 0%) 100%);
  }

  .bggarden-right {
    background: linear-gradient(90deg, #666 0%, rgb(102 102 102 / 0%) 100%);
  }

  .bottomCon{
    ::v-deep .uni-icons{
      color: #18a786 !important;
    }
  }
}

page {
  background: #f5f5f5;
}
</style>
